/**
    File        : PluginManager.cpp
    Description : Singleton class for managing all plugins
    Author      : Raymond Marsh
    Created     : 08/01/2009
    Copyright 2009, 2010, 2011, 2012 Raymond Marsh

    This program is distributed under the terms of the GNU General Public License.
    To view a copy of the license see the file 'copying.txt'

    This file is part of the MyMoney Suite.

    MyMoney is free software: you can redistribute it and/or modify it under
    the terms of the GNU General Public License as published by the Free Software Foundation, either
    version 3 of the License, or (at your option) any later version.

    MyMoney is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
    without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along with MyMoney.
    If not, see <http://www.gnu.org/licenses/>.
**/

#include "../include/MainFrame.h"
#include "../include/PluginManager.h"

CPluginManager::CPluginManager()
{

}

CPluginManager::~CPluginManager()
{

}

void CPluginManager::Initialize(CMainFram* pParent)
{
    wxASSERT_MSG(!g_IsInit, "CPluginManager can only be initalized once");
    g_IsInit= true;
    m_pParent = pParent;
}

int CPluginManager::LoadAllPlugins()
{
    // find all .dll plugin files and attempt to load them
    wxArrayString Files;
    size_t num = wxDir::GetAllFiles(mmPluginDir, &Files, mmPluginExt, wxDIR_FILES);
	for(size_t i = 0; i < num; i++)
	{
        this->LoadPlugin(Files[i] );
	}
    return m_PluginList.size();
}

void CPluginManager::UnloadAllPlugins()
{
    PLUGIN_LIST_ITER it;
    for (it = m_PluginList.begin(); it != m_PluginList.end(); ++it)
    {
        if ( (*it)->pPluginObject &&  (*it)->pLibLoader)
        {
            (*it)->pPluginObject->ShutdownPlugin();
            (*it)->pFuncUnregisterPlugin(&(*it)->pPlugin);
            delete  (*it)->pLibLoader;
            (*it)->pLibLoader            = NULL;
            (*it)->pPluginObject         = NULL;
            (*it)->pFuncRegisterPlugin   = NULL;
            (*it)->pFuncUnregisterPlugin = NULL;
        }
        delete (*it);
    }
}

CPluginBase* CPluginManager::GetPluginByName(const wxString& PluginName)
{
    PLUGIN_LIST_ITER iter;
    for (iter = m_PluginList.begin(); iter != m_PluginList.end(); ++iter)
    {
        if ( (*iter)->PluginType == PT_ACCOUNTTYPE)
        {
            if ( (*iter)->PluginName == PluginName)
            {
                return (*iter)->pPluginObject;
            }
        }
    }
    return NULL;
}

wxArrayString CPluginManager::GetAvailableAccountPluginNames()
{
    wxArrayString List;
    PLUGIN_LIST_ITER iter;
    for (iter = m_PluginList.begin(); iter != m_PluginList.end(); ++iter)
    {
        if (iter->PluginType == PT_ACCOUNTTYPE)
            List.Add(iter->PluginName);
    }
    return List;
}

bool CPluginManager::LoadPlugin(const wxString &Filename)
{
    SPluginInfo* pPlugin = new SPluginInfo;

    // initialize the wxDynamicLibrary object and attempt to load the plugin
    pPlugin->pLibLoader = new wxDynamicLibrary();
    if(pPlugin->pLibLoader->Load(Filename, wxDL_NOW) )
    {
        // if loaded successfully, check for required symbols in the DLL
        wxString err = wxEmptyString;
        if(!pPlugin->pLibLoader->HasSymbol(g_strFuncRegister) )
            err <<"\n" <<g_strFuncRegister;
        if(!pPlugin->pLibLoader->HasSymbol(g_strFuncUnregister) )
            err <<"\n" <<g_strFuncUnregister;
        if(err == wxEmptyString)
        {
            // if the required symbols are found then retrive the function pointers to those symbols
            pPlugin->pFuncRegisterPlugin = (DLLFunctionInitPtr)(pPlugin->pLibLoader->GetSymbol(g_strFuncRegister) );
            pPlugin->pFuncUnregisterPlugin = (DLLFunctionInitPtr)(pPlugin->pLibLoader->GetSymbol(g_strFuncUnregister) );

            // attempt to register the plugin with the app
            // this will return a pointer to the plugin interface if successful
            if (pPlugin->pFuncRegisterPlugin(&pPlugin->pPlugin) )
            {
                // if successful, get the name of the plugin and check that it is not already loaded
                pPlugin->PluginName    = pPlugin->pPlugin->GetPluginName();
                pPlugin->PluginType    = pPlugin->pPlugin->GetPluginType();
                pPlugin->PluginVersion = pPlugin->pPlugin->GetPluginVersionString();
                pPlugin->WXVersion     = pPlugin->pPlugin->GetWxVersionString();
                PLUGIN_LIST_ITER it;
                wxString msg = wxEmptyString;
                for (it = m_PluginList.begin(); it != m_PluginList.end(); ++it)
                {
                    // check if the plugin has already been loaded
                    if ( (*it)->PluginName == pPlugin->PluginName)
                        msg <<wxString::Format("Attempting to load plugin '%s' more than once",
                                               pPlugin->PluginName);
                }

                // check that the plugin version of wxWidgets is the same as the app's
                if (pPlugin->WXVersion != wxVERSION_STRING)
                    msg = wxString::Format("Plugin '%s' uses an incompatable version of wxWidgets.\n"
                                           "Plugin uses wxWidgets version %s\n"
                                           "and needs to use version %s.",
                                           pPlugin->PluginName,
                                           pPlugin->WXVersion,
                                           wxVERSION_STRING);

                // unload the plugin if there was an error
                if (msg !=wxEmptyString)
                {
                    // unregister and delete this instance of the plugin
                    pPlugin->pFuncUnregisterPlugin(&pPlugin->pPlugin);
                    delete pPlugin->pLibLoader;
                    delete pPlugin;
                    return;
                }

                // initialize the plugin object and add it to the list of loaded plugins
                pPlugin->pPluginObject->InitializePlugin( (IPluginHost*)this);
                if (pPlugin->PluginType = PT_ACCOUNTTYPE)
                {
                    m_pData->AddAccountTypeToList( ( (CAccountPlugin*)pPlugin->pPluginObject)->GetPluginName() );
                }
                m_PluginList.push_back(pPlugin);
            }
        }
        else
        {
            mmErrorDlg(this, wxString::Format("Required symbols not found for plugin %s -%s", Filename, err) );
            return false;
        }
    }
    else
    {
        unsigned long e = GetLastError();
        mmErrorDlg(this, wxString::Format(_("Could not load Plugin\n%s\nError Number %i"), Filename, e) );
        return false;
    }
    return true;
}

